import sys
import traceback
from datetime import datetime

from PySide6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QTextEdit, QStackedWidget, QSpacerItem, QSizePolicy, QMessageBox
)
from PySide6.QtCore import Slot, Qt, Signal

import statement, balance_sheet
from invoice import invoice_main
from ledger2others import ledger_main
from api import api_log

class MainUI(QWidget):
    send_to_subthread_signal = Signal(bool)

    GROUP_BOX_STYLE = '''
                        QGroupBox {
                            border: 1px solid #D0D0D0;
                            border-radius: 5px;
                            margin-top: 0.5em;
                            padding-top: 10px;  /* 增加顶部 padding，使标题和控件之间的距离增大 */
                        }
                        QGroupBox::title {
                            font-weight: bold !important; /* 为什么不生效？？？ */
                            subcontrol-origin: margin; /* 标题从 padding 区域开始 */
                            subcontrol-position: top left;  /* 标题从左上角开始 */
                            padding-left: 10px;             /* 标题向右移动 10px */
                            padding-right: 3px;             /* 右侧 padding 保持不变 */
                        }
                        '''
    
    def __init__(self):
        super().__init__()

        self.api_log = api_log.ApiLog()
        self.api_log.start()

        self.main_ui()

    def get_default_button_style(self):
        # 按钮样式表
        return """
            QPushButton {
                background-color: #F0F0F0;  /* 按钮背景颜色 */
                color: #333333;            /* 按钮文字颜色 */
                border: 0px; /* 边框 */
                padding: 10px;             /* 内边距 */
                font-size: 16px;           /* 字体大小 */
                border-radius: 10px;        /* 圆角 */
            }
            QPushButton:hover {
                background-color: #E0E0E0; /* 鼠标经过时按钮背景颜色 */
            }
            QPushButton:pressed {
                background-color: #B0B0B0; /* 点击后高亮颜色 */
            }
        """
    
    def get_clicked_button_style(self):
        return self.get_default_button_style().replace('background-color: #F0F0F0;', 'background-color: #D0D0D0;')
    
    def main_ui(self):
        self.button_page = {
            '结算支付台账': {'index': 0, 'text': '结算支付台账', 'widget': ledger_main.LedgerUiScroll(self.GROUP_BOX_STYLE)},
            '月报': {'index': 1, 'text': '月报', 'widget': statement.StatementUi(self.GROUP_BOX_STYLE)},
            '科目余额表': {'index': 2, 'text': '科目余额表', 'widget': balance_sheet.BalanceSheetUi(self.GROUP_BOX_STYLE)},
            '发票识别': {'index': 3, 'text': '发票识别', 'widget': invoice_main.InvoiceUiScroll(self.GROUP_BOX_STYLE)},
        }
        self.all_buttons = []
        self.setWindowTitle("PyWork")
        self.setFixedSize(800, 600)
        # self.setWindowIcon(QIcon('/res/logo.ico'))

        # 使用水平布局分割左右两部分
        main_layout = QHBoxLayout(self)
        left_panel = QWidget()        # 创建左侧功能区
        left_layout = QVBoxLayout(left_panel)
        right_layout = QVBoxLayout()
        right_layout.setSpacing(10)
        self.upper_right_panel = QStackedWidget()        # 创建右上方显示区域
        self.result_edit = QTextEdit()
        self.result_edit.setReadOnly(True)
        self.clear_edit_btn = QPushButton('清空')
        self.clear_edit_btn.clicked.connect(lambda: self.result_edit.clear())
        right_layout.addWidget(self.upper_right_panel)
        right_layout.addWidget(self.result_edit)
        right_layout.addWidget(self.clear_edit_btn, alignment=Qt.AlignRight)

        # 添加左侧功能区按钮
        for key, value in self.button_page.items():
            button = QPushButton(key)
            button.setFixedHeight(60)
            button.setStyleSheet(self.get_default_button_style())  # 设置按钮样式
            button.clicked.connect(self.button_clicked)
            left_layout.addWidget(button)


            self.all_buttons.append(button)

            # 添加右侧页面
            ui_widget = value['widget']
            ui_widget.rel_tip_signal.connect(self.add_result_tip)
            ui_widget.show_msg_signal.connect(self.show_message)
            ui_widget.log_signal.connect(self.api_log.add_log)
            self.send_to_subthread_signal.connect(ui_widget.receive_decision)
            self.upper_right_panel.addWidget(ui_widget)
        
        # 左侧设置
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(0)
        left_layout.addSpacerItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))      # 添加下方占位符

        # 默认第一个按钮被选中
        self.all_buttons[0].setStyleSheet(self.get_clicked_button_style())

        main_layout.addWidget(left_panel, stretch=2)  # 左侧占1份宽度
        main_layout.addLayout(right_layout, stretch=5)
    
    @Slot()
    def button_clicked(self):
        current_button = self.sender()
        text = current_button.text()
        self.upper_right_panel.setCurrentIndex(self.button_page[text]['index'])

        for button in self.all_buttons:
            if button == current_button:
                button.setStyleSheet(self.get_clicked_button_style())
            else:
                button.setStyleSheet(self.get_default_button_style())

    @Slot(str, str)
    def add_result_tip(self, text: str, color: str = 'dark'):
        self.result_edit.setTextColor('dark')
        current_time = datetime.now().strftime("   %H:%M:%S")
        self.result_edit.insertPlainText(f'{current_time} --> ')
        self.result_edit.setTextColor(color)
        self.result_edit.insertPlainText(f'{text}\n')
        self.result_edit.verticalScrollBar().setValue(self.result_edit.verticalScrollBar().maximum())
    
    @Slot(dict)
    def show_message(self, argvs: dict):
        message = argvs['message']      # 信号传递不支持关键字参数，又想设置默认参数来减少常规调用时传递的参数。通过字典解决
        title = argvs.get('title', '提示')
        set_btn = argvs.get('set_btn', False)

        if type(message) == tuple:
            message, title, set_btn = message
        msg_box = QMessageBox()
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        if set_btn:
            # 使用 addButton 来添加自定义按钮
            yes_button = msg_box.addButton('是', QMessageBox.YesRole)
            no_button = msg_box.addButton('否', QMessageBox.NoRole)
            # msg_box.setIcon(QMessageBox.Question)
            if msg_box.clickedButton() == yes_button:
                self.send_to_subthread_signal.emit(True)
            else:
                self.send_to_subthread_signal.emit(False)
        msg_box.exec()        # 显示消息框，会获取用户的选择，返回值为 0/1
    
    def handle_exception(self, exc_type, exc_value, exc_traceback):
        error_msg = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
        self.api_log.add_log(__name__, f'程序发生错误：\n{error_msg}')
        sys.__excepthook__(exc_type, exc_value, exc_traceback)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_ui = MainUI()
    sys.excepthook = main_ui.handle_exception
    main_ui.show()
    sys.exit(app.exec())